package com.example.arwhack.ui.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;

import androidx.annotation.StringRes;
import androidx.appcompat.app.AppCompatActivity;
import androidx.lifecycle.ViewModelProviders;

import com.example.arwhack.R;
import com.example.arwhack.ui.arw.RecordsActivity;
import com.example.arwhack.ui.login.viewmodel.LoginViewModel;

public class LoginActivity extends AppCompatActivity {

    private LoginViewModel loginViewModel;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        //初始化Activity
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_login);
        //设置viewModel
        loginViewModel = ViewModelProviders.of(this).get(LoginViewModel.class);

        //拿到Activity中的元素
        final EditText usernameEditText = findViewById(R.id.username);
        final EditText passwordEditText = findViewById(R.id.password);
        final EditText coinEditText = findViewById(R.id.coin);
        final EditText currencyText = findViewById(R.id.currency);
        final Button loginButton = findViewById(R.id.login);
        final ProgressBar loadingProgressBar = findViewById(R.id.loading);


        //保存登录信息
        //获得SharedPreferences的实例 sp_name是文件名
        SharedPreferences sp = getApplication().getSharedPreferences("arw_hack", Context.MODE_PRIVATE);
        if(!TextUtils.isEmpty(sp.getString("saved_username",null))
                &&!TextUtils.isEmpty(sp.getString("saved_password",null))
                &&!TextUtils.isEmpty(sp.getString("saved_coin",null))
                &&!TextUtils.isEmpty(sp.getString("saved_currency",null))){
            updateUiWithUser();
            return;
        }


        //输入表单变化监听
        loginViewModel.getLoginFormState().observe(this, formState -> {
            if (formState == null) {
                return;
            }
            loginButton.setEnabled(formState.isDataValid());
            if (formState.getUsernameError() != null) {
                usernameEditText.setError(getString(formState.getUsernameError()));
            }
            if (formState.getPasswordError() != null) {
                passwordEditText.setError(getString(formState.getPasswordError()));
            }
        });

        //登录结果监听
        loginViewModel.getLoginResult().observe(this, loginResult -> {
            if (loginResult == null) {
                return;
            }
            loadingProgressBar.setVisibility(View.GONE);
            if (loginResult.getError() != null) {
                showLoginFailed(loginResult.getError());
            }
            if (loginResult.getSuccess() != null) {
                //登录成功，先将登录数据保存到本地存储
                //获得Editor 实例
                SharedPreferences.Editor spEditor = sp.edit();
                //以key-value形式保存数据
                spEditor.putString("saved_username", usernameEditText.getText().toString());
                spEditor.putString("saved_password", passwordEditText.getText().toString());
                spEditor.putString("saved_coin", coinEditText.getText().toString());
                spEditor.putString("saved_currency", currencyText.getText().toString());
                spEditor.putString("saved_token",loginResult.getSuccess());
                spEditor.apply();
                //跳转到列表
                updateUiWithUser();

            }

        });

        TextWatcher afterTextChangedListener = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                // ignore
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                // ignore
            }

            @Override
            public void afterTextChanged(Editable s) {
                loginViewModel.loginDataChanged(usernameEditText.getText().toString(), passwordEditText.getText().toString());
            }
        };
        usernameEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.addTextChangedListener(afterTextChangedListener);
        passwordEditText.setOnEditorActionListener((v,actionId,event) -> {
            if (actionId == EditorInfo.IME_ACTION_DONE) {
                loginViewModel.login(usernameEditText.getText().toString(),
                        passwordEditText.getText().toString());
            }
            return false;
        });


        loginButton.setOnClickListener(v ->{
            loadingProgressBar.setVisibility(View.VISIBLE);
            loginViewModel.login(usernameEditText.getText().toString(),passwordEditText.getText().toString());
        });
    }

    private void updateUiWithUser() {
        Intent intent = new Intent(this, RecordsActivity.class);
        startActivity(intent);
        //结束当前Activity
        setResult(Activity.RESULT_OK);
        finish();
    }

    private void showLoginFailed(@StringRes Integer errorString) {
        Toast.makeText(getApplicationContext(), errorString, Toast.LENGTH_SHORT).show();
    }
}
